<template>
  <div class="edit-user-info">
    <div class="list">
      <div class="item por" :class="item.className" v-for="(item, i) in list" :key="i">
        <div class="text fl vam">{{item.text}}</div>
        <div class="inner clearfix" @click="checkItem(item.className)">
          <img
            class="avatar-img vam fr"
            :src="localId || info[item.className]"
            v-if="item.className === 'avatar'"
          />
          <van-radio-group v-model="info[item.className]" v-else-if="item.className === 'sex'">
            <van-radio class="vat dib" :name="item.value" v-for="item in sexes" :key="item.value">
              {{item.label}}
              <img
                slot="icon"
                slot-scope="{checked}"
                class="h100"
                :src="checked ? radioIcon.active : radioIcon.inactive"
              />
            </van-radio>
          </van-radio-group>
          <input
            type="text"
            class="gl-input"
            :class="item.className + '-input'"
            v-else
            :placeholder="item.placeholder"
            :readonly="item.readonly"
            v-model="info[item.className]"
          />
        </div>
        <img class="right-ico abs-m" src="../../images/center/right.png" v-show="item.needRight"/>
      </div>
    </div>
    <div class="next-btn tac" @click="next">下一步</div>
    <van-popup v-model="setAvatar" class="df-popup">
      <div class="avatar-popup tac">
        <div class="avatar-popup-title">选择方式</div>
        <div class="avatar-popup-inner flex jcb">
          <div
            class="pic-type"
            v-for="item in picTypes"
            :key="item.type"
            @click="checkPicType(item.type)"
          >
            <img :src="item.icon" alt class="type-ico vat"/>
            <div class="type-name lh1">{{item.text}}</div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
  import {mapGetters, mapMutations} from "vuex";

  export default {
    name: "EditUserInfo",
    computed: {
      ...mapGetters(["userInfo", "wxUserInfo", "turing"])
    },
    created() {
      this.testId().catch(err => {
        if (typeof err === 'string') return;
        this.$err(err);
      });
    },
    mounted() {
      //获取用户的turingkey跟id，以便后续操作
      this.getTuring()
      // this.turing.turingkey = this.$route.query.turingkey;
      // this.turing.turingid = this.$route.query.turingid;
    },
    data() {
      return {
        setAvatar: false,
        birthday: "",
        picTypes: [
          {
            text: "相机",
            icon: require("../../images/center/pic_type_03.png"),
            type: 1
          },
          {
            text: "相册",
            icon: require("../../images/center/pic_type_05.png"),
            type: 2
          }
        ],
        info: {
          avatar: "",
          nickname: "",
          birthday: "",
          sex: "2"
        },
        radioIcon: {
          active: require("../../images/center/radio_ico_03.png"),
          inactive: require("../../images/center/radio_ico_05.png")
        },
        sexes: [{label: "男", value: 1}, {label: "女", value: 2}],
        list: [
          {text: "头像", className: "avatar", needRight: true},
          {
            text: "设备昵称",
            className: "nickname",
            needRight: false,
            placeholder: "请输入设备昵称"
          },
          // {
          //   text: "生日",
          //   className: "birthday",
          //   needRight: true,
          //   placeholder: "请选择您的出生年月",
          //   readonly: true
          // },
          {text: "性别", className: "sex", needRight: false}
        ],
        localId: "",
        isLocalData: false
      };
    },
    methods: {
      ...mapMutations(["setUserInfo", "setTuring"]),
      getTuring() {
        // this.$route.query.turingkey; deviceToken
        this.setTuring(
          {
            app_id:this.$route.query.app_id,
            turingkey: this.$route.query.turingkey,
            device_token: this.$route.query.deviceToken,
            turingid: this.$route.query.turingid
          }
        )
      },
      async testId() {
        let id = this.$route.params.id;
        this.util.setWxConfig(['chooseImage', 'uploadImage']).catch(this.$err);
        if (!isNaN(id) && this.userInfo.uid * 1 !== id * 1) {
          //  绑定 25841 25842
          await this.util.login(id, this.$route.fullPath);
        } else {
          //  编辑
        }
        // console.log(this.userInfo);
        // console.log(this.wxUserInfo);
        this.info = {
          avatar: this.userInfo.icon,
          nickname: this.userInfo.nickname,
          birthday: this.userInfo.birthday
            ? this.util.formatTime(this.userInfo.birthday, "Y-MM-DD")
            : "",
          sex: this.userInfo.sex
        };
      },

      formatter(type, value) {
        return (
          value * 1 +
          {
            year: "年",
            month: "月",
            day: "日"
          }[type] || ""
        );
      },
      checkItem(type) {
        switch (type) {
          case "avatar":
            this.setAvatar = true;
            break;
          case "birthday":
            this.util.picker({
              type: "date",
              title: "选择日期",
              dfValue: new Date(this.info.birthday || new Date()),
              maxDate: new Date(),
              minDate: new Date("2000-1-1"),
              sure: this.checkBirthday,
              formatter: this.formatters
            });
            break;
          default:
          // console.log(type);
        }
      },
      checkPicType(type) {
        let _this = this;
        let sourceType = ["camera", "album"][type - 1];
        wx.chooseImage({
          count: 1, // 默认9
          sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: [sourceType], // 可以指定来源是相册还是相机，默认二者都有
          success(res) {
            _this
              .getFileUrl(res.localIds[0])
              .then(url => {
                _this.localId = url;
              })
              .catch(_this.$err);
          }
        });
        this.setAvatar = false;
      },
      checkBirthday(birthday) {
        if (birthday) {
          this.info.birthday = this.util.formatTime(birthday, "Y-MM-DD");
        }
      },
      uploadQN(file) {
        return this.http.upload("opening/upload.qupload", {
          token: "FFFX123456",
          file
        });
      },

      // 通过localId获取图片路径(base64)
      getFileUrl(localId) {
        let _this = this;
        return new Promise((res, req) => {
          wx.uploadImage({
            localId, // 图片的localID
            isShowProgressTips: 1, // 默认为1，显示进度提示
            success(data) {
              // let serverId = data.serverId; // 返回图片的服务器端ID
              // 通过serverId获取图片路径
              _this.http
                .$post("webcat/api/get_image", {
                  media_id: data.serverId
                })
                .then(img => {
                  res(img.url);
                })
                .catch(_this.$err);
            }
          });
        });
      },
      next(notSet) {
        if (notSet === true)
          return this.$router.replace({
            name: "Home"
          });
        if (this.localId) {
          let file = this.util.base2img(this.localId);
          this.uploadQN(file)
            .then(r => {
              // 修改用户信息
              this.updateInfo(r.data.savepath);
            })
            .catch(this.$err);
        } else {
          this.updateInfo();
        }
      },
      updateInfo(mc_icon = "") {
        let params = {
          uid: this.userInfo.uid,
          mc_nickname: this.info.nickname,
          mc_birthday: this.info.birthday,
          mc_sex: this.info.sex || 3,
          mc_icon
        };
        this.http
          .$post("user/api/update_info", params)
          .then(res => {
            console.log(res);
            this.$toast.success("编辑成功");
            res.uid = res.uid || res.id;
            this.setUserInfo(res);
            setTimeout(() => this.next(true));
          })
          .catch(this.$err);
      }
    }
  };
</script>

<style scoped lang="less">
  .edit-user-info {
    padding-bottom: 3.44rem;
  }

  .list {
    .right-ico {
      right: 0.94rem;
      width: 0.41rem;
      height: 0.84rem;
    }
    .item {
      padding: 0.47rem 0.94rem;
      background-color: #fff;
      line-height: 2.81rem;
      color: #333;
      font-size: 1rem;
    }
    > :not(:last-child) {
      margin-bottom: 0.06rem;
    }
    .text {
      margin-right: 1.78rem;
    }
    .avatar {
      margin-bottom: 0.63rem;
      line-height: 3.44rem;
    }
    .avatar-img {
      margin-right: 1.2rem;
      width: 3.44rem;
      height: 3.44rem;
      border-radius: 50%;
    }
    [class$="-input"] {
      background-color: transparent;
      color: #333;
      font-size: 1rem;
    }
    .van-radio {
      &:not(:last-child) {
        margin-right: 3rem;
      }
      /deep/ .van-radio__icon {
        display: inline-block;
        vertical-align: middle;
      }
    }
  }

  .next-btn {
    margin: 3.44rem 1.69rem 0;
    border-radius: 0.31rem;
    background-image: linear-gradient(90deg, #00baff, #3275ff);
    line-height: 2.81rem;
    font-size: 1rem;
    color: #fff;
    &:hover {
      background-image: linear-gradient(90deg, #00a0dc, #1762f9);
    }
  }

  .avatar-popup {
    width: 17.5rem;
    background-color: #fff;
    border-radius: 0.63rem;
    .avatar-popup-title {
      border-bottom: #eee solid 0.06rem;
      color: #333;
      font-size: 1rem;
      line-height: 2.69rem;
    }
    .avatar-popup-inner {
      padding: 1.25rem 3.28rem 1.44rem;
      font-size: 0.88rem;
      color: #666;
    }
    .type-ico {
      margin-bottom: 0.69rem;
      width: 3.44rem;
      height: 3.44rem;
    }
  }

  .birthday-popup {
    /deep/ .van-picker__toolbar {
      height: 0;
      overflow: hidden;
    }
    .birthday-title {
      padding: 0 0.78rem;
      color: #333;
      font-size: 1rem;
      line-height: 2.69rem;
      border-bottom: 0.06rem solid #eee;
      .sure {
        font-size: 0.88rem;
        color: #208fff;
      }
    }
  }
</style>
